'use strict';
const db = uniCloud.database();
const users = db.collection('users');

exports.main = async (event, context) => {
  const { action, data } = event;
  switch (action) {
    case 'login':
      return await login(data);
    case 'update':
      return await updateUser(data);
    case 'getInfo':
      return await getUserInfo(data);
    case 'updateStats':
      return await updateUserStats(data);
    default:
      return {
        code: -1,
        msg: '未知操作'
      };
  }
};

// 保存用户
async function login(data) {
  try {
    const testUser = await users.where({
      openId: data.openId
    }).get();
    if (testUser.data.length === 0) {
      // 创建测试用户
      await users.add({
        ...data,
        createTime: Date.now(),
        updateTime: Date.now()
      });
	  return {
        code: -1,
        msg: '用户未创建'
      };
    }else{
		return {
		  code: 0,
		  data: testUser.data[0]
		};
	}
  } catch (e) {
    console.error('创建用户失败:', e);
  }
}

// 更新用户统计信息
async function updateUserStats(data) {
  const { openId, isWin = false } = data;
  
  try {
    const userResult = await users.where({
      openId: openId
    }).get();
    
    if (userResult.data.length === 0) {
      return {
        code: -1,
        msg: '用户不存在'
      };
    }
    
    const user = userResult.data[0];
    const updateData = {
      gamesCount: user.gamesCount + 1,
      winningCount: isWin ? user.winningCount + 1 : user.winningCount,
      updateTime: Date.now()
    };
    
    // 计算新的胜率
    updateData.winningRate = (updateData.winningCount / updateData.gamesCount) * 100;
    
    await users.doc(user._id).update(updateData);
    
    return {
      code: 0,
      msg: '更新成功',
      data: {
        ...user,
        ...updateData
      }
    };
  } catch (e) {
    console.error('更新统计信息失败:', e);
    return {
      code: -1,
      msg: '更新失败'
    };
  }
}

// 获取用户信息
async function getUserInfo(data) {
  const { openId } = data;
  
  try {
    const result = await users.where({
      openId: openId
    }).get();
    
    if (result.data.length === 0) {
      return {
        code: -1,
        msg: '用户不存在'
      };
    }
    return {
      code: 0,
      data: result.data[0]
    };
  } catch (e) {
    console.error('获取用户信息失败:', e);
    return {
      code: -1,
      msg: '获取用户信息失败'
    };
  }
}

// 更新用户信息
async function updateUser(data) {
  const { openId, updateData } = data;
  
  try {
    const userResult = await users.where({
      openId: openId
    }).get();
    
    if (userResult.data.length === 0) {
      return {
        code: -1,
        msg: '用户不存在'
      };
    }
    
    // 添加更新时间
    updateData.updateTime = Date.now();
    
    await users.doc(userResult.data[0]._id).update(updateData);
    
    return {
      code: 0,
      msg: '更新成功',
      data: {
        ...userResult.data[0],
        ...updateData
      }
    };
  } catch (e) {
    console.error('更新用户信息失败:', e);
    return {
      code: -1,
      msg: '更新失败'
    };
  }
} 